import React, { useState, useCallback, useRef, useEffect } from 'react';
import classNames from 'classnames';
import { BtnOptionsItem } from './typing';
import { bem } from "@/utils";

export interface SkuOperateProps {
    btnOptions?: Array<BtnOptionsItem>;
    operateBtn?: React.ReactNode;
    onClientBtnOperate: (btn: BtnOptionsItem) => void;
}

const SkuOperate: React.FC<SkuOperateProps> = (props) => {
    const {
        btnOptions,
        operateBtn,
        onClientBtnOperate,
        ...rest
    } = {
        ...props
    };

    const b = bem('sku');

    // 全局加载状态和当前操作的按钮ID
    const [isProcessing, setIsProcessing] = useState(false);
    // 使用单个定时器引用
    const timerRef = useRef<NodeJS.Timeout | null>(null);
    const [disabled, setDisabled] = useState(false);

    // 处理按钮点击事件
    const clickBtnOperate = (btn: BtnOptionsItem) => {
        // 如果正在处理中，则直接返回
        if (isProcessing) return;
        setIsProcessing(true);
        setDisabled(true);

        // 执行按钮操作
        onClientBtnOperate?.(btn);

        clear();
        timerRef.current = setTimeout(() => {
            finallyBtn();
        }, 500);
    };

    const finallyBtn = () => {
        setIsProcessing(false);
        setDisabled(false);
    };

    const clear = () => {
        if (timerRef.current) {
            clearTimeout(timerRef.current);
            timerRef.current = null;
        }
    };

    useEffect(() => {

        return () => {
            clear();
        };
    }, []);

    return (
        <div className={b('operator')}>
            {
                btnOptions ? btnOptions.map((btn, i) => {
                    return (
                        <button key={btn.btnId || i}
                            className={classNames(b('operator-btn'), b('operator-btn') + `__${btn.btnClassName}`)}
                            onClick={() => clickBtnOperate(btn)}
                            disabled={disabled}
                        >
                            {btn.btnTitle}
                        </button>
                    );
                }) : null
            }
        </div>
    );
}

export default SkuOperate;